package mail;

import redis.RedisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/SendMailServlet")
public class SendMailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //2.获取请求参数
        String to=request.getParameter("to");

        //3.进行业务处理
        //生成随机验证码
        Integer code=(int)(Math.random()*(9999-1000)+1000);
//        //保存验证码到redis
//        RedisUtil.set(to,120,code+"");
        //保存验证码到session
        request.getSession().setAttribute("code",code+"");
        //发送邮件
        String text="您的验证码为："+code+"，2分钟内有效，请勿泄露于他人！";
        boolean result= MailUtil.sendMail(to,"注册验证码",text);

        //4.响应返回结果
        response.getWriter().print(result);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
